package org.zfes.snowy.sys.biz.org.service.impl;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zfes.snowy.base.dao.enums.QueryType;
import org.zfes.snowy.base.dao.params.ParamMap;
import org.zfes.snowy.core.data.ComboboVo;
import org.zfes.snowy.core.data.DataSet;
import org.zfes.snowy.core.idcenter.IDGenerator;
import org.zfes.snowy.core.util.*;
import org.zfes.snowy.sys.biz.consts.SysBizConsts;
import org.zfes.snowy.sys.biz.log.util.ZLogUtil;
import org.zfes.snowy.sys.biz.org.dao.SysOrganizationMapper;
import org.zfes.snowy.sys.biz.org.dao.SysOrganizationUserMapper;
import org.zfes.snowy.sys.biz.org.model.SysOrganization;
import org.zfes.snowy.sys.biz.org.model.SysOrganizationUser;
import org.zfes.snowy.sys.biz.org.service.ISysOrganizationService;

import java.util.*;
import java.util.stream.Stream;

//import org.zfes.snowy.base.service.BaseService;

//extends BaseService
@Service
public class SysOrganizationServiceImpl implements ISysOrganizationService {
 	@Autowired
	private SysOrganizationMapper sysOrganizationMapper;
	@Autowired
	private SysOrganizationUserMapper sysOrganizationUserMapper;

	@Transactional(rollbackFor=Exception.class)
 	@Override
	public void createSysOrganization(SysOrganization sysOrganization) {
		ZBeanUtil.validateBean(sysOrganization);
		if (ZObjectUtil.isNotEmpty(sysOrganization.getParentId())){
			Optional<SysOrganization> org = loadSysOrganizationById(sysOrganization.getParentId());
			sysOrganization.setOrgTreeCode(org.get().getOrgTreeCode()+sysOrganization.getCode());
			sysOrganization.setId(IDGenerator.genLongId());
			sysOrganizationMapper.insertSelective(sysOrganization);
		}
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<SysOrganization> loadSysOrganizationById(Long id) {
		if(id!=null){
			return Optional.ofNullable(sysOrganizationMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
		
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateSysOrganization(SysOrganization sysOrganization) {
		ZBeanUtil.validateBean(sysOrganization);
		sysOrganizationMapper.updateByPrimaryKeySelective(sysOrganization);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteSysOrganization(Long id) {
			ZAssert.notNull(id, "请选择要操作的数据");
			sysOrganizationMapper.deleteByPrimaryKey(id);
			return;
		
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setSysOrganizationStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {0,1,2}).anyMatch(val->val.equals(status))) {
			ZAssert.notNull(status, "状态参数错误");
		}
		sysOrganizationMapper.updateStatus( id,  status) ;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadSysOrganizationDataSet(Map<String, Object> params) {
		ParamMap pm= ParamMap.filterParam(params);
		DataSet ds= DataSet.newDS2(sysOrganizationMapper.selectListCount(pm), sysOrganizationMapper.selectMapList(pm));
		return ds;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<Map<String, Object>> loadOrganizationTree(Map<String, Object> params) {
		String pId= SysBizConsts.tree_table_rootnode_paarent_fk;
		Long rootId=Long.parseLong(pId);
		List<Long> rootIdList=sysOrganizationMapper.selectRootIdList(rootId);
		if(rootIdList==null || rootIdList.size()==0){
			//ZAlert.Error("未发现根节点数据，请检查数据");
			return Collections.emptyList();
		}
		if(rootIdList.size()>1){
			//	ZAlert.Error("发现多个根节点数据，请检查数据");
			return Collections.emptyList();
		}
		ParamMap pm=ParamMap.newPm(QueryType.S_O_C);
		String pid=(String) params.get("pid");
		if(ZStrUtil.hasText(pid)){
			pm.addParam("parentId", pid);
		}
		if(ZObjectUtil.isNotEmpty(params.get("level"))){
			pm.addParam("level", params.get("level"));
		}
		List<Map<String, Object>> treeList=sysOrganizationMapper.selectOrganizationTree(pm);
		return treeList;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadUserForOrganization(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		DataSet ds=null;
		Optional<String> type=pm.getStr("isInOrganization");
		if(SysBizConsts.ISINORGANIZATION.inorganization.equals(type.get())){
			ds=loadUserFormOrganization(params);
		}else if(SysBizConsts.ISINORGANIZATION.notInOrganization.equals(type.get())){
			ds=loadUserNotInOrganization(params);
		}
		return ds;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadUserFormOrganization(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		Optional<Long> organizationId=pm.getLong("organizationId");
		if(organizationId.isPresent()){
			pm.updateParam("organizationId", organizationId.get());
		}
		Optional<Long> roleId=pm.getLong("role");
		if(roleId.isPresent()){
			pm.updateParam("roleId", roleId.get());
		}
		Optional<String> perName=pm.getStr("perName");
		if(perName.isPresent()){
			pm.updateParam("perName", "%"+perName.get()+"%");
		}
		Optional<String> perNum=pm.getStr("perNum");
		if(perNum.isPresent()){
			pm.updateParam("perNum", "%"+perNum.get()+"%");
		}
		DataSet ds=DataSet.newDS(sysOrganizationUserMapper.selectUserFromOrganizationCount(pm), sysOrganizationUserMapper.selectUserFromOrganizationList(pm));
		return ds;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadUserNotInOrganization(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		Optional<Long> organizationId =pm.getLong("organizationId");
		if(organizationId.isPresent()){
			pm.updateParam("organizationId", organizationId.get());
		}
		Optional<Long> roleId=pm.getLong("role");
		if(roleId.isPresent()){
			pm.updateParam("roleId", roleId.get());
		}
		Optional<String> perName=pm.getStr("perName");
		if(perName.isPresent()){
			pm.updateParam("perName", "%"+perName.get()+"%");
		}
		Optional<String> perNum=pm.getStr("perNum");
		if(perNum.isPresent()){
			pm.updateParam("perNum", "%"+perNum.get()+"%");
		}
		DataSet ds=DataSet.newDS(sysOrganizationUserMapper.selectUserNotInOrganizationCount(pm), sysOrganizationUserMapper.selectUserNotInOrganizationList(pm));
		return ds;
	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public void addUserToOrganization(List<Long> userIds, List<Long> appIds,Long organizationId) {
		// TODO Auto-generated method stub
		if(userIds==null || ZObjectUtil.isEmpty(userIds)){
			ZAlert.Error("请选择数据");
		}
		SysOrganization organization=sysOrganizationMapper.selectByPrimaryKey(organizationId);
		if(ZObjectUtil.isEmpty(organization)){
			ZAlert.Error("组织机构不存在，请检查数据");
		}
		userIds=(List<Long>) ZBeanUtil.removeDuplicate(userIds);
		removeUserFromOrganization(userIds,organizationId);
		List<SysOrganizationUser> departmentUserList= Lists.newArrayList();
		for(Long userId:userIds){
			departmentUserList.add(new SysOrganizationUser(IDGenerator.genLongId(),organizationId,userId));
		}
		sysOrganizationUserMapper.batchInsertDepartmentUser(departmentUserList);

	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public void removeUserFromOrganization(List<Long> userIds, Long orgId) {
		if(orgId==null ||ZObjectUtil.isEmpty(userIds)){
			ZAlert.Error("请选择数据");
		}
		sysOrganizationUserMapper.deleteUserFromDeptment(userIds,orgId);
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public SysOrganization selectSysOrganizationListByUserId(Long userId) {
		if(userId!=null){
			SysOrganization sys = sysOrganizationMapper.selectSysOrganizationList(userId);
			if(ZObjectUtil.isNotEmpty(sys)){
				return sys;
			}

		}
			return null;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<Map<String, Object>> loadOrganizationTabelDic() {
		String level = null;
		List<Map<String,Object>> list = sysOrganizationMapper.loadOrganizationByLevelCode(level);
		if (ZObjectUtil.isNotEmpty(list) && list.size() > 0){
			return list;
		}else{
			return Collections.emptyList();
		}
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<ComboboVo> selectOrgranizationComboboV( Boolean firstEmpty,String level,Long pid) {
		Map<String, Object> map = new HashMap<>();
		map.put("level", level);
		map.put("pid", pid);
		ParamMap pm = ParamMap.filterParam(map);
		List<ComboboVo> list = sysOrganizationMapper.selectOrgranizationComboboV(pm);
		List<ComboboVo> orgList2 = new ArrayList<>();
		if(firstEmpty != null && firstEmpty){
			orgList2.add(0, ComboboVo.newEmptyFirst());
		}
		orgList2.addAll(list);

		return orgList2;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public SysOrganization selectSysOrganizationListByName(String name) {
		SysOrganization sys = sysOrganizationMapper.selectSysOrganizationListByName(name);
		if(ZObjectUtil.isNotEmpty(sys)){
			return sys;
		}
		return null;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public SysOrganization selectSysOrganizationListByCode(String code) {
		SysOrganization sys = sysOrganizationMapper.selectSysOrganizationListByCode(code);
		if(ZObjectUtil.isNotEmpty(sys)){
			return sys;
		}
		return null;
	}
}